//
//  MTScatterChart.m
//  MTPanleChart
//
//  Created by Coollang on 16/7/27.
//  Copyright © 2016年 fei. All rights reserved.
//

#import "MTScatterChart.h"
#import "PNChart.h"
#import "NSBundle+CurrentLanguage.h"


#define MTScatterChartHeight  (self.bounds.size.height)
#define MTScatterChartWidth   (self.bounds.size.width)
#define MTScreenWidth   ([UIScreen mainScreen].bounds.size.width)

@interface MTScatterChart ()
@property (nonatomic, strong) CAShapeLayer *xLayer; // x轴
@property (nonatomic, strong) CAShapeLayer *yLayer;  // y轴

@property (nonatomic, strong) NSMutableArray *xTextLayers;  // x轴 下的文本CATextLayer

@property (nonatomic, strong) NSMutableArray *yTextLayers;  // y轴 边的文本CATextLayer

/** 添加圆点 */
@property (nonatomic, strong) NSMutableArray *scatterDotArray;

/** 缓存虚线 */
@property (nonatomic, strong) NSMutableDictionary *dashlineCache;
@property (nonatomic, strong) NSMutableDictionary *dashTextLayerCache;

/** 圆点的大小 */
@property (nonatomic, assign)CGSize dotSzie;


@property (nonatomic, strong) CATextLayer *dotTextLayer;

@end

@implementation MTScatterChart
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [self setupDefualtValuse];
        [self setDefaultValues];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder]) {
        [self setupDefualtValuse];
    }
    
    return self;
}

- (void)setDefaultValues {
    _xAxisStartPoint = CGPointMake(30, MTScatterChartHeight - 12);
    _xAxisEndPoint = CGPointMake(MTScatterChartWidth -  _xAxisStartPoint.x - 20,_xAxisStartPoint.y);
    _yAxisStartPoint = _xAxisStartPoint;
    _yAxisEndPoint = CGPointMake(_yAxisStartPoint.x, 8);
}

// 设置默认值
- (void)setupDefualtValuse {
    // 设置xy轴的默认值
    _isShow_xAxis = YES;
    _isShow_yAxis = YES;
    
    _axisColor = kBackgroundColorDeep;

    _axisLineWidth = 1.0f;
   
    _xTextLayers = [NSMutableArray array];
    _yTextLayers = [NSMutableArray array];
    _xAxisTextGap = 3;    _yAxisTextGap = 2;
    _xAxisTextFont = [UIFont systemFontOfSize:11];
    _xAxisTextColor = kUnSelectedColor;
    _yAxisTextColor = kUnSelectedColor;
    _yAxisTextFont = _xAxisTextFont;
    _scatterDotArray = [NSMutableArray array];
    
    // 虚线
    _dashlineCache = [NSMutableDictionary dictionary];
    _dashTextLayerCache = [NSMutableDictionary dictionary];
}

/**
 *  创建xy轴
 */
- (void)createAxisChart{
    
    // 先清空之情的xy轴
    [_xLayer removeFromSuperlayer];
//    [_yLayer removeFromSuperlayer];
    
    // 创建x轴
    if (!_isShow_xAxis) {
        return;
    }
    _xLayer = [CAShapeLayer layer];
    UIBezierPath *xPath = [UIBezierPath bezierPath];
    [xPath moveToPoint:_xAxisStartPoint];
    [xPath addLineToPoint:_xAxisEndPoint];
    _xLayer.path = xPath.CGPath;
    _xLayer.strokeColor = _axisColor.CGColor;
    _xLayer.lineWidth = _axisLineWidth;
    [self.layer addSublayer:_xLayer];
    
    // 创建y轴
    if(!_isShow_yAxis)
        return;
    if (!_yLayer) {
        _yLayer = [CAShapeLayer layer];
        [self.layer addSublayer:_yLayer];
    }
    
    UIBezierPath *yPath = [UIBezierPath bezierPath];
    [yPath moveToPoint:_yAxisStartPoint];
    [yPath addLineToPoint:_yAxisEndPoint];
    _yLayer.path = yPath.CGPath;
    _yLayer.strokeColor = _axisColor.CGColor;
    _yLayer.lineWidth = _axisLineWidth;
    
}
/**
 *  创建坐标轴周围显示文字
 */
- (void)createAxisTtiles{
    
    // 1.先清除之前的layer
    if (_xTextLayers) {
        for (CALayer *layer in _xTextLayers) {
            [layer removeFromSuperlayer];
//            [_xTextLayers removeObject:layer];
        }
    }
    if (_yTextLayers) {
        for (CALayer *layer in _yTextLayers) {
            [layer removeFromSuperlayer];
//            [_yTextLayers removeObject:layer];
        }
    }

    // x 轴方向的文字
    for (int i = 0; i < _xTitleArray.count; i++) {
        CATextLayer *textLayer = [CATextLayer layer];
        textLayer.foregroundColor = _xAxisTextColor.CGColor;

        textLayer.string = [_xTitleArray[i] stringValue];
        textLayer.contentsScale = [UIScreen mainScreen].scale;
        textLayer.font = (__bridge CFTypeRef _Nullable)(_xAxisTextFont.fontName);
        textLayer.fontSize = _xAxisTextFont.pointSize;
        textLayer.alignmentMode = kCAAlignmentCenter;
        textLayer.bounds = CGRectMake(0, 0, 30, 16);
        CGFloat xAxisMargin = 0;
        if (_xTitleArray.count > 1) {
           xAxisMargin = fabs(_xAxisEndPoint.x - _xAxisStartPoint.x) / (_xTitleArray.count - 1);
        }
         
        
         textLayer.position = CGPointMake(_xAxisStartPoint.x + xAxisMargin * i, _xAxisStartPoint.y + _xAxisTextGap);
        textLayer.anchorPoint = CGPointMake(0.5, 0);
        [self.layer addSublayer:textLayer];
        [_xTextLayers addObject:textLayer];
    }
    
    
    // y 轴方向的文字
    for (int i = 0; i < _yTitleArray.count; i++) {
        CATextLayer *textLayer = [CATextLayer layer];
        textLayer.foregroundColor = _yAxisTextColor.CGColor;
        
        textLayer.string = [_yTitleArray[i] stringValue];
        textLayer.font = (__bridge CFTypeRef _Nullable)(_yAxisTextFont.fontName);
        textLayer.fontSize = _yAxisTextFont.pointSize;
        textLayer.alignmentMode = kCAAlignmentRight;
        textLayer.bounds = CGRectMake(0, 0, 30, 16);
        textLayer.contentsScale = [UIScreen mainScreen].scale;
    
        CGFloat  textLayerX = _yAxisStartPoint.x - _yAxisTextGap;
        CGFloat yAxisMargin = 0;
        if (_yTitleArray.count > 1) {
            yAxisMargin = fabs(_yAxisEndPoint.y - _yAxisStartPoint.y ) / (_yTitleArray.count - 1);
        }
        
        
        CGFloat  textLayerY = _yAxisStartPoint.y - yAxisMargin * i;
        textLayer.position = CGPointMake(textLayerX, textLayerY);
        textLayer.anchorPoint = CGPointMake(1, 0.5);
        
        [self.layer addSublayer:textLayer];
        [_yTextLayers addObject:textLayer];
        
    }

}
// 添加虚线
- (void)drawDash:(NSNumber *)targetValue lineHeight:(CGFloat)lineHeight lineLength:(CGFloat)lineLength lineSpacing:(CGFloat)lineSpacing lineColor:(UIColor *)lineColor withString:(NSString *)text textColor:(UIColor *)textColor{
    
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.bounds = CGRectMake(0, 0, fabs(_xAxisEndPoint.x - _xAxisStartPoint.x), 3);
    shapeLayer.strokeColor = lineColor.CGColor;
    shapeLayer.lineWidth = lineHeight;
    
    [_yTitleArray.lastObject floatValue];
    
    CGFloat shapeLayerY = _yAxisStartPoint.y - (fabs(_yAxisEndPoint.y - _yAxisStartPoint.y) * targetValue.floatValue) / [_yTitleArray.lastObject floatValue];
    
    shapeLayer.position = CGPointMake(_yAxisStartPoint.x, shapeLayerY);
    shapeLayer.anchorPoint = CGPointMake(0, 0.5);
    [shapeLayer setLineJoin:kCALineJoinRound];
    
    [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:@(lineLength), @(lineSpacing), nil]];
    
    //  设置路径
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, 0);
    CGPathAddLineToPoint(path, NULL, fabs(_xAxisEndPoint.x - _xAxisStartPoint.x), 0);
    [shapeLayer setPath:path];
    CGPathRelease(path);
    //  把绘制好的虚线添加上来
    [self.layer addSublayer:shapeLayer];
    [_dashlineCache setObject:shapeLayer forKey:text];

    
    // 添加一个解释文字
    CATextLayer *textLayer = [CATextLayer layer];
    
    textLayer.string = text;
    textLayer.font = (__bridge CFTypeRef _Nullable)([UIFont systemFontOfSize:11]);
    textLayer.foregroundColor = textColor.CGColor;
    
    CGSize textSize =  [self text:text MaxSize:CGSizeMake(MAXFLOAT, MAXFLOAT) font:[UIFont systemFontOfSize:11]];
    textLayer.contentsScale = [UIScreen mainScreen].scale;
    textLayer.bounds = CGRectMake(0, 0, textSize.width, textSize.height);
    textLayer.fontSize = [UIFont systemFontOfSize:11].pointSize;
    
    textLayer.position = CGPointMake(_xAxisEndPoint.x, shapeLayer.position.y);
    textLayer.anchorPoint = CGPointMake(0, 0.5);
    
    [self.layer addSublayer:textLayer];
    [_dashTextLayerCache setObject:textLayer forKey:text];

}


// 添加圆点视图
- (void)updateScatterDotLayer {
    

    for (CALayer *layer in _scatterDotArray) {
        [layer removeFromSuperlayer];
        //[_scatterDotArray removeObject:layer];
    }
    
    switch (self.dotItems.count / 20) {
        case 0:
            self.dotSzie = CGSizeMake(4, 4);
            break;
        case 1:
            self.dotSzie = CGSizeMake(4, 4);
            break;
        case 2:
            self.dotSzie = CGSizeMake(4, 4);
            break;
        case 3:
            self.dotSzie = CGSizeMake(4, 4);
            break;
        default:
            self.dotSzie = CGSizeMake(4, 4);
            break;
    }
    // 标注最大速度
    NSNumber *maxNumber = [self maxNumber];
    
    for (NSInteger i = 0; i < self.dotItems.count; i++) {
        
        // 取出拍速
        CGFloat swingSpeed = [self.dotItems[i] floatValue];
        
        CALayer *dotLayer = [CALayer layer];
  
        dotLayer.bounds = CGRectMake(0, 0, self.dotSzie.width, self.dotSzie.height);
        dotLayer.cornerRadius = dotLayer.bounds.size.width * 0.5;
        
        UIColor *backgroundColor = swingSpeed >= _targetSpeed ? kSelectedColor:kUnSelectedColor;
        dotLayer.backgroundColor = backgroundColor.CGColor;
        
        CGFloat positionX = _xAxisStartPoint.x + (fabs(_xAxisEndPoint.x - _xAxisStartPoint.x) / (self.dotItems.count + 1)) * (i + 1);
        
        CGFloat positionY = _yAxisStartPoint.y - (fabs(_yAxisEndPoint.y - _yAxisStartPoint.y) * swingSpeed) / [_yTitleArray.lastObject floatValue];
        
        if (positionY < _yAxisStartPoint.y - (fabs(_yAxisEndPoint.y - _yAxisStartPoint.y))) {
            
            positionY = _yAxisStartPoint.y - (fabs(_yAxisEndPoint.y - _yAxisStartPoint.y));
        }
        
        dotLayer.position = CGPointMake(positionX, positionY);
        dotLayer.anchorPoint = CGPointMake(0.5, 1);
        
        if ([maxNumber floatValue] == swingSpeed) {
            if (self.dotTextLayer) {
                [self.dotTextLayer removeFromSuperlayer];
            }
            CATextLayer *textLayer = [CATextLayer layer];
            NSString *text = maxNumber.stringValue;
            textLayer.string = text;
            
            textLayer.font = (__bridge CFTypeRef _Nullable)([UIFont systemFontOfSize:11]);
            textLayer.foregroundColor = kOrangeColor.CGColor;
            CGSize textSize =  [self text:text MaxSize:CGSizeMake(MAXFLOAT, MAXFLOAT) font:[UIFont systemFontOfSize:11]];
            
            textLayer.contentsScale = [UIScreen mainScreen].scale;
            textLayer.bounds = CGRectMake(0, 0, textSize.width, textSize.height);
            textLayer.fontSize = [UIFont systemFontOfSize:11].pointSize;
            
            textLayer.position = CGPointMake(dotLayer.position.x, dotLayer.position.y - _dotSzie.height - 1);
            textLayer.anchorPoint = CGPointMake(0.5, 1);
            
            [self.layer addSublayer:textLayer];
            self.dotTextLayer = textLayer;
        }
        
        [self.layer addSublayer:dotLayer];
        [_scatterDotArray addObject:dotLayer];
    }
    if (self.dotItems.count == 0) {
        if (self.dotTextLayer) {
            [self.dotTextLayer removeFromSuperlayer];
        }
    }
}


- (NSNumber *)maxNumber {

    NSArray *array = [self.dotItems sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:nil ascending:YES]]];
    
    return array.lastObject;
}

- (void)updateTargetSpeed:(CGFloat)targetSpeed withTextString:(NSString *)textString {
    NSString *keyText = [NSString stringWithFormat:@"%@\n%.0fkm/h",textString,_targetSpeed];
    
    [_dashTextLayerCache[keyText] removeFromSuperlayer];
    [_dashlineCache[keyText] removeFromSuperlayer];
    [_dashlineCache removeObjectForKey:keyText];
    [_dashTextLayerCache removeObjectForKey:keyText];
    
    for (CALayer *layer in _dashTextLayerCache.allValues) {
        [layer removeFromSuperlayer];
    }
    
    for (CALayer *layer in _dashlineCache.allValues) {
        [layer removeFromSuperlayer];
    }
    
    
    _targetSpeed = targetSpeed;
    
    NSString *targetString = textString;
    if (![NSBundle currentLanguageIsChinese]) {
        targetString = NSLocalizedString(@"RealTime.Target", nil);//@"Target";
    }
    
    
    [self drawDash:@(targetSpeed) lineHeight:0.5 lineLength:2 lineSpacing:2 lineColor:[UIColor redColor] withString:[NSString stringWithFormat:@"%@\n%.0fkm/h",targetString,targetSpeed] textColor:[UIColor colorWithHex:0x7c7b80 alpha:0.8]];
}

// 计算文本的大小
- (CGSize)text:(NSString *)str MaxSize:(CGSize)maxSize font:(UIFont *)font
{
    NSDictionary *attr = @{NSFontAttributeName : font};
    return [str boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attr context:nil].size;
}

/**
 *  绘制图形
 */
- (void)drawChart{

    [self createAxisChart];
    [self createAxisTtiles];
    [self updateScatterDotLayer];
}


@end
